package week03.question03.gateway02.filter;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;

/**
 * 实现一个代理时间统计的Filter
 */
public class ProcessCalculateFilter implements HttpResponseFilter, HttpRequestFilter {
    private ThreadLocal<Long> localStorage = new ThreadLocal<>();

    @Override
    public void filter(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
        //放置时间戳
        localStorage.set(System.currentTimeMillis());
    }

    @Override
    public void filter(FullHttpResponse response) {
        long curr = System.currentTimeMillis();
        Long aLong = localStorage.get();
        long diff = curr - aLong;
        double seconds = diff/1000.0;
        System.out.println("spend times : "+seconds+"s!");
        response.headers().set("cost", seconds);
        localStorage.remove();
    }
}
